import os
import re
from scrapy.exporters import JsonItemExporter
from items.ugitems import SongItem, DetailItem
from fpdf import FPDF

"""
完整一页信息
"""


class UltimateGuitarPipeline(object):
    # name="UltimateGuitarPipeline"
    def open_spider(self, spider):
        # print("open_spider",spider)
        self.file = open("./temp/page_data.json", "wb")
        self.exporter = JsonItemExporter(self.file, ensure_ascii=False)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        print("process_item in UltimateGuitarPipeline.", item)
        # print("item type:",type(item))
        self.exporter.export_item(item)
        # items = item["store"]["page"]["data"]["data"]["tabs"]
        # for it in items:
        #     print('it-->',it)
        # self.exporter.export_item(it)
        # yield it

        return item

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()
        return


"""
处理Artist信息SongItem,存入artist_data.json中
"""


class ArtistPipeline(object):
    def __init__(self):
        self.file = open("./temp/artist_data.json", "wb")
        self.exporter = JsonItemExporter(self.file, ensure_ascii=False)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        if isinstance(item, SongItem):
            # print("process_item in artistPipeline.",item)
            self.exporter.export_item(item)
        return item


"""
处理DetailItem
"""


class DetailPipeline(object):
    def __init__(self):
        self.file = open("./temp/detail_data.json", "wb")
        self.exporter = JsonItemExporter(self.file, ensure_ascii=False)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        if isinstance(item, DetailItem):
            # print("process_item in artistPipeline.",item)
            item["tab_content"] = self.cleanContent(item["tab_content"])
            self.write_file(item)
            self.exporter.export_item(item)
        return item

    def cleanContent(self, content):
        newstr = re.sub(r"\[ch\]", "    ", content)
        newstr = re.sub(r"\[(\/ch|tab|\/tab)\]", "     ", newstr)
        return newstr

    def write_file(self, item):
        artistName = item["artist_name"]
        filename = item["song_name"] + "_" + str(item["song_id"]) + ".txt"
        
        pdffilename = item["song_name"] + "_" + str(item["song_id"]) + ".pdf"
        file_path = "./temp/files/" + artistName + "/" + filename
        pdf_file_path = "./temp/files/" + artistName + "/" + pdffilename
        # 1. 分离目录和文件名
        dir_name = os.path.dirname(file_path)
        # 2. 创建目录（如果不存在）
        if dir_name:
            os.makedirs(dir_name, exist_ok=True)  # exist_ok=True防止目录已存在时报错

        # 3. 创建空文件（如果文件不存在）
        if not os.path.exists(file_path):
            # 使用写入模式打开文件会自动创建
            with open(file_path, "w", encoding="utf-8") as f:
                pass  # 空操作，仅创建文件
            print(f"文件已创建：{file_path}")
        else:
            print(f"文件已存在：{file_path}")
            
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(item["tab_content"])
        
        self.txt_to_pdf(file_path, pdf_file_path)

    '''
    写入pdf
    '''
    def txt_to_pdf(self, input_file, output_file):
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)
        
        # 读取 TXT 文件内容
        with open(input_file, "r", encoding="utf-8") as file:
            text = file.read()
        
        # 将文本写入 PDF（自动处理换行和分页）
        pdf.multi_cell(w=0, h=10, txt=text)
        pdf.output(output_file)